package me.zxhm.plugin.beacon;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.widget.Toast;

import org.altbeacon.beacon.BeaconConsumer;
import org.altbeacon.beacon.BeaconManager;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * This class echoes a string called from JavaScript.
 */
public class Beacon extends CordovaPlugin {

    protected static final String TAG = "BeaconPlugin";



    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("toast")) {
            String message = args.getString(0);
            this.toast(message, callbackContext);
            return true;
        }
        else if (action.equals("getBeacons"))
        {
            this.getBeacons(callbackContext);
            return true;
        }
        else if (action.equals("startService"))
        {
            this.startService(callbackContext);
            return true;
        }
        else if (action.equals("stopService"))
        {
            this.stopService(callbackContext);
            return true;
        }
        return false;
    }

    /**
     * 开启服务
     * @param callbackContext
     */
    public void startService(CallbackContext callbackContext)
    {
        if (verifyBluetooth())
        {
            Intent intent = new Intent(cordova.getContext(), BeaconService.class);
            cordova.getActivity().startService(intent);
            callbackContext.success();
        }
        else
        {
            callbackContext.error("低功耗蓝牙不可用");
        }
    }

    /**
     * 停止服务
     * @param callbackContext
     */
    public void stopService(CallbackContext callbackContext)
    {
        Intent intent = new Intent(cordova.getContext(), BeaconService.class);
        cordova.getActivity().stopService(intent);
        callbackContext.success();
    }

    /**
     * 获取Beacon设备
     * @param callbackContext
     */
    public void getBeacons(CallbackContext callbackContext)
    {
        try {
            JSONArray value = new JSONArray();
            for (BeaconDto beacon:BeaconService.beaconList) {
                value.put(beacon.toJSON());
            }
            callbackContext.success(value);
        }
        catch (Exception e)
        {
            callbackContext.error(e.getMessage());
        }
    }

    public void toast(String message, CallbackContext callbackContext)
    {
        if (message != null && message.length() > 0) {
            Toast.makeText(cordova.getContext(),message,Toast.LENGTH_SHORT).show();
            callbackContext.success("显示成功");
        } else {
            callbackContext.error("Expected one non-empty string argument.");
        }
    }

    /**
     * 确认蓝牙可用
     */
    private boolean verifyBluetooth() {
        boolean access = true;
        try {
            if (!BeaconManager.getInstanceForApplication(cordova.getActivity()).checkAvailability()) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(cordova.getContext());
                builder.setTitle("蓝牙没有打开");
                builder.setMessage("请在设置中打开蓝牙，然后重启APP");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        cordova.getActivity().finishAffinity();
                    }
                });
                builder.show();
                access = false;
            }
        }
        catch (RuntimeException e) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(cordova.getContext());
            builder.setTitle("低功耗蓝牙不可用");
            builder.setMessage("您的设备不支持低功耗蓝牙，请更换设备");
            builder.setPositiveButton(android.R.string.ok, null);
            builder.setOnDismissListener(new DialogInterface.OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog) {
                    cordova.getActivity().finishAffinity();
                }

            });
            builder.show();
            access = false;
        }
        return  access;
    }
}